package entity.lemming;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;

import entity.Entity;
import entity.terrain.Terrain;
import level.Level;

/**
 * A lemming that drops slowly to the floor. Prevents a Lemming dying on impact.
 * 
 * @author Neil Cowzer, Olga Murdoch
 */
public class Floater extends Lemming {
	
	private int count;

	/**
	 * 
	 * @param x the starting x-coordinate.
	 * @param y the starting y-coordinate.
	 */
	/*@ requires 0 <= x && 0 <= y;
		assignable speed_X && speed_Y && energy;
		ensures speed_X == 0 && speed_Y < 0 && energy == 100;
	 */
	public Floater(int x, int y){
		super("resource/graphics/lemming/floater/floater1.gif",12, x, y);
		speed_X = 0;
		speed_Y = 1;
		energy = 100;
		count = 0;
	}
	
	/**
	 * Create a new Floater with the given center point
	 * 
	 * @param center point of the Lemming
	 */
	public Floater(Point center){
		super("resource/graphics/lemming/floater/floater1.gif",12, center);
		speed_X = 0;
		speed_Y = 1;
		energy = 100;
	}
	
	/**
	 * Checks for a collision with certain Entities
	 * 
	 * @param other another Entity eg Terrain, Lemming.
	 * @return true if a collision has occured.
	 */
	public /*@ pure @*/ boolean collision(Lemming other) {
		// TODO Auto-generated method stub
		return false;
	}

	/** Request that this lemming perform the appropiate action/movement. */
	/*@ ensures x == \old(x) &&
	 * 			y == \old(y) + speed_Y &&
				energy == \old(energy) - 1;
	 */
	public void move(Terrain terrain) {
		count++;
		Rectangle lemming = getBounds();
		
		if (lemming.intersects(terrain.getBounds())){
			BufferedImage image = ((Terrain)terrain).getImage().getBufferedImage();
				int black = -16777216; // black that represents the background
				int black2 = -16776960;
				
				try{
					for (int curr_x = getX(); curr_x < getX() + lemming.width; curr_x++){
						int color = 0;
						
							color = image.getRGB(curr_x, y+lemming.height);
						
							// if we have a pixel to stand on
							if (color != black){
								if(color != black2){
									energy = 1;
								} else{
									energy = 1;
								}
								break;
							}
					}
				}catch(ArrayIndexOutOfBoundsException e){
					
				}
				}
			if (count%2 != 0){
				y= y+speed_Y;
			}
			if (count == 8){
				generateFrames("resource/graphics/lemming/floater/floater2r.gif", 2);
			}
			update();
			energy--;
	}
	
	/** Override turnAround. */
	public void turnAround(){
		// do nothing!
	}

}
